package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.business.entity.Result;
import com.example.business.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/a")
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @PostMapping(value = "/signin")
    public JSONObject signin(SysUser sysUser, HttpServletRequest request) {
        SysUser user = new SysUser();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getName(), sysUser.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            // 所以这一步在调用login(token)方法时,它会走到xxRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            subject.login(token);

            user = (SysUser) subject.getPrincipal();
            //获取sessionId
            String sessionId = (String) subject.getSession().getId();
            // 执行到这里说明用户已登录成功
        } catch (LockedAccountException lockedAccountException) {
            return Result.error("error", lockedAccountException.toString());
        } catch (UnknownAccountException unknownAccountException) {
            return Result.error("error", "不存在的账号，请先注册账号后登录。");
        } catch (AccountException accountException) {
            return Result.error("error", accountException.toString());
        } catch (Exception e) {
            logger.error("登录失败，用户名[{}]", sysUser.getName(), e);
            String exception = e.toString();
            token.clear();
            return Result.error("error", "登录失败:" + exception);
        }
        return Result.success(JSON.toJSONString(user));
    }

//    @PostMapping(value = "/getRouters")
//    public JSONObject getRouters () {
//
//    }
}
